﻿var MB = window["MB"] || {}
MB.page = MB["page"] || {}
MB.page.perSchedule = (function ($) {
    var settings = {
        isDTInited: {
            new_order: false,
            current_order: false,
            workshop: false,
            schedule:false
        },
        currentSchedule: {
            id: 0,
            code: '新建排程',
            status:1
        }
    }
   
    var select_model = {
        new_order: []
        , current_order: []
        ,schedule:[]
    }
    var url_model = {
        new_order: '/PreProduce/GetPreduceComs',
        current_order: '/PreProduce/GetCurrentPreduceComs',
        schedule: '/PreProduce/SearchSchedule',
        workshop:'/PreProduce/GetScheduleWorkshop'
    }
    var common = MB.page.common
    var isInit = true

    var initWorkshopTable = function (model) {

        var grid = '#' + model + '_grid'
        var form = '#' + model + '_form'
        if (settings.isDTInited[model] == true) {
            $(form).submit();
            return
        } else
            settings.isDTInited[model] = true
        $(grid).dataTable().fnDestroy();
        $(grid).dataTableExtention({
            "scrollY":"100px",
            "initLoadFormParams": true,
            "filterForm": form,
            "ordering": false,
            "paging":false,
            "pageLength": 100,
            "pagingType": "bootstrap_full_number",
            "language": {
                "sProcessing": "处理中...",
                "sLengthMenu": "",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "",
                "sInfoEmpty": "",
                "sInfoFiltered": "",
                "sInfoPostFix": "",
                "sSearch": "搜索:",
                "sUrl": "",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                },
                "oAria": {
                }
            },
            "sAjaxSource": url_model[model],
            "order": [
                [0, "asc"]
            ],
            "aoColumns": [
            { "mDataProp": "WORKSHOP_NAME" },
            { "mDataProp": "WORKSHOP_CODE" },
            { "mDataProp": "(NET_CAPACITY - PRODUCE_COUNT)" }
            ],
            "columnDefs": [{

                "orderable": false,
                "targets": [0],
                "render": function (data, type, row) {
                    var completeCount = row.PRODUCE_COUNT * 1
                    var totalCount = row.NET_CAPACITY * 1
                    return '<div style="height:24px;width:110px" data-capacity="' + (totalCount - completeCount) + '" data-type="item" data-id="' + row.ID + '" data-model="workshop" ><span >' + row.WORKSHOP_NAME + '</span></div>'
                }
            },
                {

                    "orderable": false,
                    "targets": [1],
                    "render": function (data, type, row) {
                        var completeCount = row.PRODUCE_COUNT * 1
                        var totalCount = row.NET_CAPACITY * 1
                        return '<div style="height:24px;width:110px" data-capacity="' + (totalCount - completeCount) + '" data-type="item" data-id="' + row.ID + '" data-model="workshop" ><span >' + row.WORKSHOP_CODE + '</span></div>'
                    }
                },
                {

                "orderable": false,
                "targets": [2],
                "render": function (data, type, row) {
                    var completeCount = row.PRODUCE_COUNT * 1
                    var totalCount = row.NET_CAPACITY * 1
                    if (totalCount !== 0) {
                        return '<div data-capacity="' + (totalCount - completeCount) + '" style="width:300px;" data-type="item" data-id="' + row.ID + '" data-model="workshop" class="graph"><span class="green" style="width:' + (completeCount / totalCount) * 100 + '%;">' + completeCount + '/' + totalCount + '</span></div>'
                    } else {
                        return '<div data-capacity="0" style="width:300px;" data-type="item" data-id="' + row.ID + '" data-model="workshop" class="graph"><span class="green" style="width: 0%;"></span></div>'
                    }
                }
            }],
            "drawCallback": function () {
               
                
            },

            "footerCallback": function (row, data, start, end, display) {
            }
        });
    }
    var initScheduleTable = function (model) {
        
        var grid = '#' + model + '_grid'
        var form = '#' + model + '_form'
        if (settings.isDTInited[model] == true) {
            $(form).submit();
            return
        } else
            settings.isDTInited[model] = true
        $(grid).dataTable().fnDestroy();
        $(grid).dataTableExtention({
            "initLoadFormParams": true,
            "filterForm": form,
            "ordering": false,
            "sAjaxSource": url_model[model],
            "pageLength":common.pageSize,
            "aoColumns": [
             { "mDataProp": null },
            { "mDataProp": "SCHEDULE_CODE" },
            { "mDataProp": "SCHEDULE_START_TIME" },
            { "mDataProp": "SCHEDULE_END_TIME" },
            { "mDataProp": "STATUS_TEXT" },
            { "mDataProp": "PRODUCING_COUNT" }
            ],
            "columnDefs": [{
                "orderable": false,
                "targets": [0],
                "render": function (data, type, row) {
                    var style=' class="btn btn-xs green" '
                    if (row.STATUS == "1") {
                        return '<a op-type="delete"  class="btn btn-xs green"  data-model="schedule" data-id="' + row.ID + '">删除</a>'
                                + '<a op-type="edit" class="btn btn-xs green" data-model="schedule" data-id="' + row.ID
                            + '" data-code="' + row.SCHEDULE_CODE + '" data-status="1" >编辑</a>'
                    } else {
                        return '<a op-type="read" class="btn btn-xs green" data-model="schedule" data-id="' + row.ID + '" '
                        + 'data-code="'+ row.SCHEDULE_CODE+'" data-status="2" >详情</a>'
                    }
                }
            }, {

                "orderable": false,
                "targets": [2],
                "render": function (data, type, row) {

                    var value = row.SCHEDULE_START_TIME.GetDate()
                    return value
                }
            }, {

                "orderable": false,
                "targets": [3],
                "render": function (data, type, row) {

                    var value = row.SCHEDULE_END_TIME.GetDate()
                    return value
                }
            }, {

                "orderable": false,
                "targets": [5],
                "render": function (data, type, row) {
                    var completeCount = (row.PRODUCE_COUNT - row.PRODUCING_COUNT) * 1
                    var totalCount = row.PRODUCE_COUNT * 1
                    var currentDate = (new Date()).Format("yyyy-MM-dd hh:mm:ss")
                    
                    var planEndDate = row.SCHEDULE_END_TIME.GetDate()
                    if (planEndDate != '' && currentDate > planEndDate && completeCount == 0) {
                        
                        return '<div class="graph warning"><span class="green" style="width:' + completeCount / totalCount + '%;">' + completeCount + '/' + totalCount + '</span></div>'
                    }
                    if (totalCount !== 0) {
                        return '<div class="graph"><span class="green" style="width:' + completeCount / totalCount + '%;">' + completeCount + '/' + totalCount + '</span></div>'
                    } else {
                        return '<div class="graph"><span class="green" style="width: 0%;"></span></div>'
                    }
                }
            }],

            "footerCallback": function (row, data, start, end, display) {
            }
        });
    }
   
    var initOrderTable = function (model) {
        setSelectNumber(model)
        var grid = '#' + model + '_grid'
        var form = '#' + model + '_form'
        if (settings.isDTInited[model] == true) {
            $(form).submit();
            return
        } else
            settings.isDTInited[model] = true
        $(grid).dataTable().fnDestroy();
        $(grid).dataTableExtention({
            "scrollY": "200px",
            "initLoadFormParams": true,
            "filterForm": form,
            "ordering": false,
            "pageLength": common.pageSize,
            "sAjaxSource": url_model[model],
            "aoColumns": [
            { "mDataProp": null },
            { "mDataProp": "ORDER_CODE" },
            { "mDataProp": "PRE_CODE" },
            { "mDataProp": "CUSTOMER_NAME" },
            { "mDataProp": "COM_NAME" },
            { "mDataProp": "FABRIC_NAME" },
            { "mDataProp": "COLOR_NAME" },
            { "mDataProp": "ORDER_COUNT" }
            ],
            "columnDefs": [{
                "orderable": false,
                "targets": [0],
                "render": function (data, type, row) {
                    for (var i = 0; i < select_model[model].length; i++) {
                        if (select_model[model][i] == row.ID) {
                            return '<input op-type="check" data-model="'+model+'" type="checkbox" checked="checked" class="checkbox" data-id="' + row.ID + '" />'
                        }
                    }
                    return '<input op-type="check" data-model="' + model + '" type="checkbox" class="checkbox" data-id="' + row.ID + '" />'
                    
                }
            }],
            
            "drawCallback": function () {
               
                $('a[op-type="selectAll"][data-model="' + model + '"]').attr('select-all',false)
            },
            
            "footerCallback": function (row, data, start, end, display) {
            }
        });
    }

    var getProduceCounts = function () {
        $.post("/PreProduce/GetProduceCount"
            , {
                "SCHEDULE_ID": settings.currentSchedule.id
            }, function (data) {
                if (data.IsSuccess === true) {
                    $('#produce_counts').text(' (总件数:' + data.Data[0].PRODUCE_COUNTS + ')')
                    $('#produce_counts').attr('data-num', data.Data[0].PRODUCE_COUNTS)
                }
            },'json')
    }
    var setSelectNumber = function (model) {
        $('#' + model + '_selected').text('已选择' + select_model[model].length + '个订单')
    }
    var selectAll = function (model) {
        $('input[op-type="check"][data-model="'+model+'"]').each(function () {
            $(this).attr('checked', 'checked')
            select_model[model].removeElement($(this).attr('data-id'))
            select_model[model].push($(this).attr('data-id'))
        })
        setSelectNumber(model)
    }
    var deSelectAll = function (model) {
        $('input[op-type="check"][data-model="' + model + '"]').each(function () {
            $(this).removeAttr('checked')
            select_model[model].removeElement($(this).attr('data-id'))
        })
        setSelectNumber(model)
    }
    var saveScheduleOrder = function (model) {
        if (select_model[model].length <= 0) {
            bootbox.alert({
                size: "small",
                animate: false,
                closeButton: false,
                className: "green-control",
                message: '未选中订单!'
            }); return;
        }
        if (settings.currentSchedule.id == 0) {
            var request = {
                PRE_PRODUCE_IDs: select_model[model]
            }
            $.post("/PreProduce/AddSchedule"
                ,{
                    "rawrequest": JSON.stringify(request)
                }
                , function (data) {
                    if (data.IsSuccess === true) {
                        var result = data.Data[0]
                        initModalSettings({
                            id:result.ID,
                            code:result.SCHEDULE_CODE,
                            status:1
                        })
                        initOrderTable('new_order')
                        bootbox.confirm({
                            size: "small",
                            animate: false,
                            closeButton: false,
                            className: "green-control",
                            message: '添加成功,点击确定回到排程详情',
                            callback: function (result) {
                                if (result == true) $('#newOrders').modal('hide')
                            }
                        })
                    } else {
                        bootbox.alert({
                            size: "small",
                            animate: false,
                            closeButton: false,
                            className: "green-control",
                            message: '添加失败,请稍后再试'
                        })
                    }
                },'json')
        } else {
            var request = {
                PRE_PRODUCE_IDs: select_model[model],
                SCHEDULE_ID: settings.currentSchedule.id
            }
            $.post("/PreProduce/AddScheduledetail"
                    , {
                        "rawrequest": JSON.stringify(request)
                    }
                    , function (data) {
                        if (data.IsSuccess === true) {
                            initModalSettings(settings.currentSchedule)
                            initOrderTable('new_order')
                            bootbox.confirm({
                                size: "small",
                                animate: false,
                                closeButton: false,
                                className: "green-control",
                                message: '添加成功,点击确定回到排程详情',
                                callback: function (result) {
                                    if(result==true) $('#newOrders').modal('hide')
                                }
                            })
                        } else {
                            bootbox.alert({
                                size: "small",
                                animate: false,
                                closeButton: false,
                                className: "green-control",
                                message: '添加失败,请稍后再试'
                            })
                        }
                    }, 'json')
        }
    }
    var deleteScheduleOrderDetail = function (model) {
        if (select_model['current_order'].length == null) {
            bootbox.alert({
                size: "small",
                animate: false,
                closeButton: false,
                className: "green-control",
                message: '未选中订单'
            })
            return
        }
        if ($('#SCHEDULE_ID').val() == 0) {
            bootbox.alert({
                size: "small",
                animate: false,
                closeButton: false,
                className: "green-control",
                message: '不需要删除'
            })
            return
        }
        var request = {
            PRE_PRODUCE_IDs: select_model['current_order'],
            SCHEDULE_ID: settings.currentSchedule.id
        }
        $.post("/PreProduce/DeleteScheduledetail"
            , {
                "rawrequest": JSON.stringify(request)
            }
            , function (data) {
                if (data.IsSuccess === true) {
                    initModalSettings(settings.currentSchedule)
                    bootbox.alert({
                        size: "small",
                        animate: false,
                        closeButton: false,
                        className: "green-control",
                        message: '删除成功'
                    })
                } else {
                    bootbox.alert({
                        size: "small",
                        animate: false,
                        closeButton: false,
                        className: "green-control",
                        message: '删除失败'
                    })
                }
            }, 'json')
    }
    var deleteSchedule = function (that) {

        $.post("/PreProduce/DeleteSchedule"
    , {
        "ID": $(that).attr('data-id')
    }
    , function (data) {
        if (data.IsSuccess === true) {
           initScheduleTable('schedule')
           bootbox.alert({
               size: "small",
               animate: false,
               closeButton: false,
               className: "green-control",
               message: '删除成功'
           })
        } else {
            bootbox.alert({
                size: "small",
                animate: false,
                closeButton: false,
                className: "green-control",
                message: '删除失败'
            })
        }
    }, 'json')
    }
    var occupyProduce = function (model, forced) {
        if(forced === undefined) forced = false
        if ($('tr.selected').length === 0) {
            bootbox.alert({
                size: "small",
                animate: false,
                closeButton: false,
                className: "green-control",
                message: '请先选择车间'
            }); return;
        }
        if ($('#produce_counts').text().indexOf('(总件数:0)') > -1) {
            bootbox.alert({
                size:"small",
                animate: false,
                closeButton: false,
                className: "green-control",
                message: '请先添加订单'
            }); return;
        }
        var produceCount = $('#produce_counts').attr('data-num') * 1
        var workshopCapacity = $('tr.selected').eq(0).attr('data-capacity') * 1
        if ((produceCount > workshopCapacity) && forced != true)
        {
            bootbox.confirm({
                size: "small",
                animate: false,
                closeButton:false,
                className:"green-control",
                message: "该车间产能不足,是否继续指派生产?",
                callback: function (result) {
                    if (result === true) {
                        occupyProduce(model, true)
                    }
                }
            });
            return;
        }
        var workshopId = $('tr.selected').eq(0).attr('data-id')
        $.post("/PreProduce/OccupyToProduce",
            {
                "SCHEDULE_ID": settings.currentSchedule.id,
                "WORKSHOP_ID": workshopId
            }, function (data) {
                if (data.IsSuccess == true) {
                    bootbox.confirm({
                        size: "small",
                        animate: false,
                        closeButton: false,
                        className: "green-control",
                        message: "已下发,是否退出当前页?",
                        callback: function (result) {
                            if (result === true) {
                                $('#mySchdedule').modal('hide')
                            }
                        }
                    })
                    initModalSettings({
                        id: settings.currentSchedule.id,
                        code: settings.currentSchedule.code,
                        status:2
                    })
                    initScheduleTable('schedule')
                }
            })
    }

    var initModalSettings = function (scheduleData) {
        settings.currentSchedule = scheduleData
        $('*[data-name="SCHEDULE_ID"]').each(function () {
            $(this).val(settings.currentSchedule.id)
        })
        $('*[data-name="SCHEDULE_STATUS"]').each(function () {
            $(this).val(settings.currentSchedule.status)
        })
        select_model = {
            new_order: []
            , current_order: []
            ,schedule:[]
        }
        $('#scheduleTitle').text(settings.currentSchedule.code)
        initOrderTable('current_order')
        
        getProduceCounts()
        initWorkshopTable('workshop')        
        if (settings.currentSchedule.status == 2) {
            $('*[op-type][data-model!="schedule"]').each(function () {
                var operation = $(this).attr('op-type')
                if(operation!=="tab" && operation != "query") $(this).hide()
            })
        } else {
            $('*[op-type][data-model!="schedule"]').each(function () {
                $(this).show()
            })
        }
    }

    var initModalEvent = function () {
        $('#reset').click(function () {
            initModalSettings({
                id: 0,
                code: '新建排程',
                status: 1
            })
        })
        $('a[op-type="save"]').click(function () {
            var model = $(this).attr('data-model')
            saveScheduleOrder(model)
            initScheduleTable('schedule')
        })
        $('*[op-type="query"]').click(function () {
            var model = $(this).attr('data-model')
            initOrderTable(model)
        })
        $('*[op-type="delete"]').click(function () {
            deleteScheduleOrderDetail($(this).attr('data-model'))
        })
        $('*[op-type="add"][data-model="current_order"]').click(function () {
            initOrderTable('new_order')
            $('#newOrders').modal()
        })
        $(document).on('click', 'a[op-type="selectAll"]', function () {
            var model = $(this).attr('data-model')
            if ($(this).attr('select-all') === "false") {
                selectAll(model)
                $(this).attr('select-all', "true")
            } else {
                deSelectAll(model)
                $(this).attr('select-all', "false")
            }
        })
        $(document).on('click', 'input[op-type="check"]', function () {
            var model = $(this).attr('data-model')
            if ($(this).attr('checked') === 'checked') {
                select_model[model].removeElement($(this).attr('data-id'))
                select_model[model].push($(this).attr('data-id'))
            } else {
                select_model[model].removeElement($(this).attr('data-id'))
            }
            setSelectNumber(model)
        })
        
        $('*[op-type="tab"]').click(function () {
            var model = $(this).attr('data-model')
            if (model != 'workshop') initOrderTable(model)
            else initWorkshopTable(model)
        })

        $('a[op-type="occupy"]').click(function () {
            occupyProduce()
        })
        $(document).on('click', '*[data-type="item"][data-model="workshop"]', function () {

            $('tr.selected').each(function () {
                $(this).removeClass('selected')
            })
            $(this).parents('tr:first').addClass('selected')
            $(this).parents('tr:first').attr('data-id', $(this).attr('data-id'))
            $(this).parents('tr:first').attr('data-capacity',$(this).attr('data-capacity'))
        })
    }


    var initContainerEvent = function () {
        
        $('#btnSchedule').click(function () {
            initModalSettings({id:0,code:"新建排程",status:1})
            $('#mySchdedule').modal('show')
        })
        $('*[op-type="querySchedule"][data-model="schedule"]').click(function () {
            initScheduleTable('schedule')
        })
        $(document).on('click', 'a[op-type="edit"][data-model="schedule"]', function () {
            initModalSettings({
                id: $(this).attr('data-id'),
                code: $(this).attr('data-code'),
                status: $(this).attr('data-status')
            })
            $('#mySchdedule').modal('show')
        })
        $(document).on('click', 'a[op-type="delete"][data-model="schedule"]', function () {
            var that = this
            deleteSchedule(that)
        })
        $(document).on('click', 'a[op-type="read"][data-model="schedule"]', function () {
            initModalSettings({
                id:$(this).attr('data-id'),
                code:$(this).attr('data-code'),
                status:$(this).attr('data-status')
            })

            $('#mySchdedule').modal('show')
        })
        initScheduleTable('schedule')
    }

    var initEvent = function () {
        initContainerEvent()
        initModalEvent()
    }

    return {
        initEvent: initEvent
    }
})(jQuery)
$(document).ready(function () {
    MB.page.perSchedule.initEvent()
})
/*
$(document).ready(function () {
    $('#selectAll').click(function () {
        if ($(this).parent().hasClass('checked') == false) {
            $('input[data-type="item"]').each(function () {
                $(this).attr('checked', 'checked')
                MB.page.perSchedule.common.addArrayData(MB.page.perSchedule.settings.ids,$(this).attr('id'))
            })
        } else {
            $('input[data-type="item"]').each(function () {
                $(this).removeAttr('checked', 'checked')
                MB.page.perSchedule.common.removeArrayData(MB.page.perSchedule.settings.ids, $(this).attr('id'))
            })
        }
        console.log(MB.page.perSchedule.settings.ids)
    })
    $('input[data-type="item"]').click(function () {
        if ($(this).attr('checked') === 'checked') {
            MB.page.perSchedule.common.addArrayData(MB.page.perSchedule.settings.ids, $(this).attr('id'))
        } else {
            MB.page.perSchedule.common.removeArrayData(MB.page.perSchedule.settings.ids, $(this).attr('id'))
        }
    })
    $('#new_orders_tab').click(function () {
        MB.page.perSchedule.initDataTable()
    })
    $('#cbx_all').click(function () {
        if ($('#cbx_all').attr('checked') === 'checked') {
            $('input[name="cbx_item"]:checkbox').each(function () {
                $(this).attr('checked', 'checked')
                $(this).parent().addClass('checked')
            })
        } else {
            $('input[name="cbx_item"]:checkbox').each(function () {
                $(this).removeAttr('checked')
                $(this).parent().removeClass('checked')
            })
        }
    })
    $('#btnSave').click(function () {

        //$('#timeLine').modal('show')
    })
    $('#btnSchedule').click(function () {
        if (MB.page.perSchedule.settings.isDTInited === false) {
            MB.page.perSchedule.initDataTable()
            MB.page.perSchedule.settings.isDTInited = true
        }
        $('#mySchdedule').modal('show')

        console.log($(".pagination .active > a").html())
    })
})
*/